package com.itic.market.mobile.jd;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itic.appbase.framework.utils.MD5Helper;
import com.itic.market.mobile.jd.MallJdConfig;
import com.jcabi.http.Request;
import com.jcabi.http.request.ApacheRequest;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.request.cps.ServicePromotionWxsqGetCodeBySubUnionIdRequest;
import com.jd.open.api.sdk.response.cps.ServicePromotionWxsqGetCodeBySubUnionIdResponse;

public class MallJdUtils {
    
	private static String baseUrl = "http://yhjcms.jhjvip.cn";
	private static String unionId = "1000169071";
	private static String access_token  = MallJdConfig.getAccesstoken();
	private static String app_key  = MallJdConfig.getKey();
	private static String app_secret  = MallJdConfig.getSecret();
	private static String jd_api_url = MallJdConfig.getUrl();
	
	
	public static JSONArray queryProductList(int pageIndex, int pageSize) {
		JSONObject req = new JSONObject();
		req.put("page", pageIndex + 1);
		req.put("pageSize", pageSize);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdProductService/queryProductList.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp).getJSONObject("result").getJSONArray("description");
		} catch (Exception e) {
			return null;
		}
	}


	public static String convert(String userId, String sku, String couponUrl) {
		userToChannel(userId);
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("subUnionId", unionId);
		Map<String, String> pcmap = new HashMap<>();
		pcmap.put(sku, couponUrl);
		req.put("pcmap", pcmap);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/couponGetCodeBySubUnionId.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //  
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp).getJSONObject("result").getJSONObject("urlList")
					.getString(couponUrl + "," + sku);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String subConvert( String skuId,String positionId ){
		JdClient client=new DefaultJdClient(jd_api_url,access_token,app_key,app_secret);
		String codeBySubUnionId	 = null; //返回链接
		ServicePromotionWxsqGetCodeBySubUnionIdRequest requestJd = null;//普通转链请求
		ServicePromotionWxsqGetCodeBySubUnionIdResponse responseJd = null; //普通转链返回
		try {
			requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
			requestJd.setProCont( 1 ); //推广内容：1单品
			requestJd.setMaterialIds(skuId); //推广物料：单品skuId
			requestJd.setPositionId(Integer.parseInt(positionId));
			responseJd=client.execute(requestJd);
			//解析返回参数
			if( "0".equals(responseJd.getCode()) ){
				String result2 = responseJd.getGetcodebysubunionidResult();
				if( result2.contains("urlList") ){
					JSONObject urls = JSON.parseObject(result2).getJSONObject("urlList");
					for (String key : urls.keySet()) {
						key = (String) urls.get(key);
						codeBySubUnionId = key;
					}
				}
			}
		} catch (JdException e) {
			e.printStackTrace();
		}
   		return codeBySubUnionId;
	}
	

	
	public static Map<String, String> convert(String userId, Map<String, String> skuMaptoCouponUrl) {
		Map<String, String> result = new HashMap<>();
		userToChannel(userId);
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("subUnionId", unionId);
		req.put("pcmap", skuMaptoCouponUrl);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/couponGetCodeBySubUnionId.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			JSONObject urls = JSON.parseObject(resp).getJSONObject("result").getJSONObject("urlList");
			for (String key : urls.keySet()) {
				result.put(key.substring(key.lastIndexOf(",") + 1), urls.getString(key));
			}
			return result;
		} catch (Exception e) {
			return null;
		}
	}

	


	public static JSONObject queryCommissionByUserId(String userId, long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/getCommissionByUserid.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	public  static JSONObject queryOrderList(long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/OrderDetail.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	
	public static JSONObject orderSettlementDetail(long startTimestamp, long endTimestamp) {
		JSONObject req = new JSONObject();
		req.put("start", startTimestamp);
		req.put("end", endTimestamp);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/orderSettlementDetail.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}

	
	public static JSONObject userToChannel(String userId) {
		JSONObject req = new JSONObject();
		req.put("userid", userId);
		try {
			String resp = new ApacheRequest(baseUrl + "/JDService/jdservice/userToChannel.json")//
					.method(Request.POST) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 京东发送HTTP请求
	 * @param url
	 * @return
	 */
	public static JSONObject toJos(String url) {
		JSONObject req = new JSONObject();
		try {
			String resp = new ApacheRequest(url)//
					.method(Request.GET) //
					.header("Content-Type", "application/json") //
					.body().set(req.toJSONString()).back() //
					.fetch().body();
			return JSON.parseObject(resp);
		} catch (Exception e) {
			return null;
		}
	}
	
	
	/**
	 * 创建京东签名
	 */
	@SuppressWarnings("rawtypes")
	public static String createSign(String secret,SortedMap<Object,Object> parameters){  
        StringBuffer sb = new StringBuffer();
        sb.append(secret);
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            Object v = entry.getValue();  
            if(null != v && !"".equals(v)   
                    && !"sign".equals(k) && !"key".equals(k)) {  
                sb.append(k +  v );  
            }  
        }  
        sb.append(secret);  
        String sign = MD5Helper.md5(sb.toString()).toUpperCase();  
        return sign;  
    }  
}